package com.guanzi.netty.server.handler;

import com.guanzi.netty.message.GroupChatRequestMessage;
import com.guanzi.netty.message.GroupCreateRequestMessage;
import com.guanzi.netty.message.GroupCreateResponseMessage;
import com.guanzi.netty.server.session.Group;
import com.guanzi.netty.server.session.GroupSession;
import com.guanzi.netty.server.session.GroupSessionFactory;
import com.guanzi.netty.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Set;

@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();

        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, members);
        if (group == null) {
            // 创建成功消息
            ctx.writeAndFlush(new GroupCreateResponseMessage(true, "【" + groupName + "】创建成功"));

            // 发送拉群消息
            for (String member : members) {
                Channel channel = SessionFactory.getSession().getChannel(member);
                channel.writeAndFlush(new GroupCreateResponseMessage(true, "你加入了【" + groupName + "】群，可以开始聊天了"));
            }
        } else {
            // 创建失败
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, "【" + groupName + "】已经存在"));
        }
    }
}
